package com.yfree.utils.net;

import com.google.gson.Gson;
import com.yfree.YConfig;
import com.yfree.models.YPostModel;
import com.yfree.models.YRootModel;
import com.yfree.utils.YAESCrypt;
import com.yfree.utils.YGZipUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

public class YResponseUtils {
    private static Gson gson = new Gson();

    public static boolean isSuccess(Object t) {
        return getCode(t).equals("1");
    }

    public static <T> ArrayList<T> getResultList(Object t, Class<T> classOfT) {
        try {
            ArrayList<T> lists = new ArrayList<>();
            YPostModel<T> YPostModel = gson.fromJson(deCompress(t), YPostModel.class);
            YRootModel<T> YRootModel = YPostModel.getRoot();
            T[] results = YRootModel.getResult();
            for (T result : results) {
                lists.add(gson.fromJson(new JSONObject((Map<String, String>) result).toString(), classOfT));
            }
            return lists;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    public static String getCode(Object t) {
        try {
            return t == null ? "" : gson.fromJson(deCompress(t), YPostModel.class).getRoot().getCode();
        } catch (Exception e) {
            return "";
        }
    }

    public static String getErrorMessage(Object t) {
        try {
            String message = gson.fromJson(deCompress(t), YPostModel.class).getRoot().getMessage();
            return YConfig.DEBUG ? "网络请求回执message：\n" + message : message;
        } catch (Exception e) {
            return YConfig.DEBUG ? "网络请求回执message解析异常，响应字符串：\n" + (t != null ? deCompress(t) : "（空）") : "网络请求错误，请重试";
        }
    }

    public static String compress(YJsonKV kv) {
        try {
            return YConfig.compressParamsAble ? (YGZipUtils.compress(YConfig.encryptParamsAble ? new YAESCrypt(YConfig.encryptParamsKey).encrypt(kv.toString().trim()) : kv.toString().trim())) : kv.toString().trim();
        } catch (Exception ignored) {
            return "";
        }
    }

    public static String deCompress(Object t) {
        try {
            String deCompressStr = YConfig.compressParamsAble ? YGZipUtils.deCompress(t.toString().trim()) : t.toString().trim();
            return YConfig.encryptParamsAble ? new YAESCrypt(YConfig.encryptParamsKey).decrypt(deCompressStr) : deCompressStr;
        } catch (Exception ignored) {
            return "";
        }
    }
}
